package com.wyix.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangdx
 * @since 2025/8/5
 */
// 注解配置：URL映射为/test，启动时加载（1表示优先级）
@WebServlet(urlPatterns = "/test", loadOnStartup = 1)
public class TestServlet extends HttpServlet {

    // 初始化方法：Servlet实例创建后调用一次
    @Override
    public void init() {
        System.out.println("TestServlet初始化");
    }

    // 处理GET请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取请求参数
        String name = request.getParameter("name");
        if (name == null) name = "Guest";

        // 输出响应
        response.getWriter().write("<h1>Hello, " + name + "</h1>");
    }

    // 处理POST请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 处理表单提交（类似doGet，需设置请求编码）
        request.setCharacterEncoding("UTF-8");
        String data = request.getParameter("data");
        response.getWriter().write("收到POST数据：" + data);
    }

    // 销毁方法：Servlet卸载前调用一次
    @Override
    public void destroy() {
        System.out.println("TestServlet销毁");
    }
}